import re
import time
import serial
# 已经调试OK


def BT_reboot(ser:serial.Serial,time_out=0.5,max_time=5):
    exStr = f'REBOOT=0'
    length = len(exStr)
    mask = re.compile(exStr)    # 模版
    ser.timeout= time_out
    try:
        send_str = 'AT+REBOOT\r\n'        # 断开连接
        ser.write(send_str.encode())  # 发送数据成功
        max_time = max_time

        start_time = time.time()

        data = ''
        while time.time() - start_time < max_time:  # 做了最大停顿时间的处理
            if not exStr:
                return True,'NO'
            temp = ser.read(1)
            if temp != b'':
                data += temp.decode()
            else:
                print('接收数据', data, temp)
                if exStr and len(data) >= length and temp == b'':
                    # print('jj',data)
                    match_list = mask.findall(data)
                    if match_list:
                        print('检查接收到的数据：', data, match_list)
                        return True, match_list[0]  # 返回匹配成功，和匹配的值
                    else:
                        return False, None  # 匹配失败
                else:
                    print('检查为接收到数据的时间，未接收到数据')
    except Exception as e:
        print('报错',e)
    return False, None



if __name__ == '__main__':
    ser = serial.Serial('com4', baudrate=961200, timeout=0.1)
    if ser.isOpen():
        print('串口已打开')
        flag, value = BT_reboot(ser)
        print('最终接收到的数据：',flag, value)
    else:
        print('串口打开失败')